import React from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'
import { withFormik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'

import { Link } from 'react-router-dom'

import NavHeader from '../../components/NavHeader'

import axios from '../../utils/request'
import { setToken } from '../../utils/token'

import styles from './index.module.css'

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/

const Login = () => {
  return (
    <div className={styles.root}>
      {/* 顶部导航 */}
      <NavHeader className={styles.navHeader}>账号登录</NavHeader>
      <WhiteSpace size="xl" />

      {/* 登录表单 */}
      <WingBlank>
        <Form>
          <div className={styles.formItem}>
            <Field
              className={styles.input}
              name="username"
              placeholder="请输入账号"
              // onChange={this.handleUserName}
            />
          </div>
          {/* 长度为5到8位，只能出现数字、字母、下划线 */}
          <ErrorMessage
            component="div"
            className={styles.error}
            name="username"
          ></ErrorMessage>
          {/* <div className={styles.error}>账号为必填项</div> */}
          <div className={styles.formItem}>
            <Field
              className={styles.input}
              name="password"
              type="password"
              placeholder="请输入密码"
              // onChange={this.handlePwd}
            />
          </div>
          {/* 长度为5到12位，只能出现数字、字母、下划线 */}
          <ErrorMessage
            component="div"
            className={styles.error}
            name="password"
          ></ErrorMessage>
          {/* <div className={styles.error}>账号为必填项</div> */}
          <div className={styles.formSubmit}>
            <button className={styles.submit} type="submit">
              登 录
            </button>
          </div>
        </Form>
        <Flex className={styles.backHome}>
          <Flex.Item>
            <Link to="/registe">还没有账号，去注册~</Link>
          </Flex.Item>
        </Flex>
      </WingBlank>
    </div>
  )
}

const MyEnhancedForm = withFormik({
  mapPropsToValues: () => ({ username: '', password: '' }),
  handleSubmit: async (values, { props }) => {
    const res = await axios.post('/user/login', values)
    // console.log('登录结果：', res)
    const { status, body, description } = res
    if (status === 200) {
      // 登录成功
      // 将 token 保存到本地缓存中
      setToken(body.token)
      //返回上一页
      props.history.go(-1)
    } else if (status === 400) {
      // 登录失败
      Toast.info(description, 2)
    }
  },
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required('用户名为必填项')
      .matches(REG_UNAME, '长度为5到8位，只能出现数字、字母、下划线'),
    password: Yup.string()
      .required('密码为必填项')
      .matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线')
  })
})(Login)

export default MyEnhancedForm
